import React from 'react';
import {Icon,Message} from 'antd';
import {Link} from 'react-router';
import {LOGIN,SEND_SMS_CODE,BIND_PHONE} from '../../constants/userTypes';
import {setItem, getItem} from '../../utils';
import config,{ REG } from '../../config';
/**
 * 加载公共组件
 * */

import MainSection from '../../components/MainSection/MainSection';

/**
 * 加载样式或图片文件
 * */
import './sass/login.scss';


class Login extends React.Component {
    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };

    constructor(props) {
        super(props);
        this.handleBindPhone = this.handleBindPhone.bind(this);
        this.sendSmsCode = this.sendSmsCode.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.state = {
            phone: '',
            smsCode: '',
            sendFlag: false,
            leftSeconds: 60,
            phoneVisible: true,
            errorVisible: false,
            errMessage: ''
        };
    }
    
    componentDidMount(){
        const {location} = this.props;
        let openid = location.query.openid;
        let token = location.query.token;
        openid && setItem('openid',openid);
        token && setItem('token',token);

        if( (openid && token) || ( getItem('openid')&&getItem('token') )){
            this.context.router.push(getItem('NEXT_URL') || '/activityList');
        }
    }
    
    sendSmsCode() {
        const { actions } = this.props;
        let phone = this.state.phone;
        if (phone === "") {
            Message.info(REG.phone.nullMsg);
            return false;
        } else if (!REG.phone.rule.test(phone)) {
            Message.info(REG.phone.errMsg);
            return false;
        }
        actions.sendSmsCode({type: 105, phone: phone}).then(res => {
            if(res.type === SEND_SMS_CODE) {
                if(res.data.code === 20000){
                    if (!this.state.sendFlag) {
                        this.setState({
                            sendFlag: true,
                            phoneVisible: false

                        });
                        this.countdown();
                    }
                }else{
                    Message.info(res.data.message);
                }

            }
        });
    }
    countdown() {
        this.timer = setInterval(() => {
            this.setState({
                leftSeconds: this.state.leftSeconds - 1
            });
            if (this.state.leftSeconds <= 0) {
                clearInterval(this.timer);
                this.setState({
                    sendFlag: false
                });
            }
        }, 1000);
    }

    componentWillUnmount(){
        clearInterval(this.timer);
    }

    handleBindPhone(e) {
        const {actions,location} = this.props;
        this.setState({smsCode: e.target.value});
        if(e.target.value.length === 4){
            actions.bindPhone({
                phone: this.state.phone,
                captcha: e.target.value,
                openid: getItem('openid')
            }).then(res=>{
                if(res.type === BIND_PHONE){
                    if(res.data.code === 20000){
                        setItem('token',res.data.data.accesstoken);

                        this.context.router.push(getItem('NEXT_URL'));
                    }else{
                        this.setState({
                            errMessage:res.data.message
                        })
                    }
                }
            });
        }
    }

    handleSubmit() {

    }

    render() {
        const {location} = this.props;
        let phoneFlag = !!this.state.phone.length;
        return (
            <MainSection className="login" title="登录">
                <div className="phone-modal">
                    <div className="title">登录 <Link to="/activityList"><Icon type="close"/></Link></div>
                    {
                        !!this.state.errMessage ? (
                            <div className="err">{this.state.errMessage}</div>
                        ) : null
                    }
                    {
                        this.state.phoneVisible ? (
                            <div className="content">
                                <div className="input-wrap">
                                    <input type="number"
                                           onChange={e => this.setState({phone:e.target.value})}
                                           value={this.state.phone}
                                           placeholder="请输入手机号码"
                                           maxLength="11"/>
                                </div>
                                <button className={"confirm-btn " + (phoneFlag ? "" : "disabled")}
                                        onClick={phoneFlag ? this.sendSmsCode : ''}>确定
                                </button>
                            </div>

                        ) : (
                            <div className="content">
                                <div className="sms-wrap">
                                    <span>{this.state.phone}</span>
                                    <button className={'sms-code ' + (this.state.sendFlag ? 'disabled' : '' )}
                                            onClick={ this.sendSmsCode }>
                                        { this.state.sendFlag ? this.state.leftSeconds + 's后重发' : '重新发送' }
                                    </button>
                                </div>
                                <div className="mock-input">
                                    <input type="text"
                                           onChange={this.handleBindPhone}
                                           maxLength="4"/>
                                    <em>{this.state.smsCode.charAt(0) || ''}</em>
                                    <em>{this.state.smsCode.charAt(1) || ''}</em>
                                    <em>{this.state.smsCode.charAt(2) || ''}</em>
                                    <em>{this.state.smsCode.charAt(3) || ''}</em>

                                </div>
                            </div>
                        )
                    }
                </div>

            </MainSection>
        );
    }
}

export default Login;